package test;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;

import javax.swing.JFrame;
import javax.swing.JLabel;

import networkedmodules.Module;
import networkedmodules.ModuleGroup;
import networkedmodules.Update;


@SuppressWarnings("serial")
public class SimpleModule extends Module implements Serializable
{
	private ClickableJLabel label;
	
	public SimpleModule(String s)
	{
		label = new ClickableJLabel();
		JFrame frame = new JFrame(s);
		frame.add(label);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String args[])
	{
		ModuleGroup hostGroup = new ModuleGroup(2380);
		ModuleGroup clientGroup = new ModuleGroup("127.0.0.1", 2380);
		SimpleModule simpleHost = new SimpleModule("Host");
		SimpleModule simpleClient = new SimpleModule("Client");
		hostGroup.addModule(simpleHost);
		clientGroup.addModule(simpleClient);
	}
	
	private class ClickableJLabel extends JLabel implements MouseListener
	{
		int value;
		public ClickableJLabel()
		{
			super("0");
			this.addMouseListener(this);
		}
		
		private void increment()
		{
			value++;
			setText("" + value);
		}

		@Override
		public void mouseClicked(MouseEvent e)
		{
			increment();
			getModuleGroup().sendUpdate(new SimpleModuleUpdate(-1));
		}

		public void mouseEntered(MouseEvent e){}
		public void mouseExited(MouseEvent e){}
		public void mousePressed(MouseEvent e){}
		public void mouseReleased(MouseEvent e){}
	}
	
	private class SimpleModuleUpdate extends Update
	{
		int value;
		
		public SimpleModuleUpdate(int i)
		{
			System.out.println("Value being sent is " + label.value);
			value = i;
			setKey(getKey());
		}
		
		@Override
		public void performUpdate(Module module)
		{
			SimpleModule simple = (SimpleModule)module;
			if(module.getModuleGroup().getType() == ModuleGroup.HOST)
			{
				simple.label.increment();
				System.out.println("Host incremented to " + simple.label.value);
				module.getModuleGroup().sendUpdate(new SimpleModuleUpdate(simple.label.value));
			}
			else
			{
				simple.label.value = value;
				simple.label.setText("" + value);
			}
		}
		
	}
}
